package com.syp.auth.web.resource;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.syp.auth.domain.KeyValuePair;
import com.syp.auth.domain.ProcessResult;
import com.syp.auth.domain.ValidateResult;
import com.syp.auth.export.common.GeneralAccessVo;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.export.common.SigninParamEnum;
import com.syp.auth.export.dto.request.TokenVerifyRequest;
import com.syp.auth.export.dto.response.TokenVerifyResponse;
import com.syp.auth.export.resource.AuthorizeResourceI;
import com.syp.auth.service.business.AuthorizeServiceI;
import com.syp.auth.service.validator.SigninErrorTypeEnum;
import com.syp.auth.service.validator.SigninValidatorI;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/api/authorize")
public class AuthorizeResourceImpl implements AuthorizeResourceI {

	@Autowired
	private HttpServletRequest httpRequest;
	@Autowired
	private HttpServletResponse httpResponse;
	@Autowired
	private AuthorizeServiceI authorizeService;
	@Autowired
	private SigninValidatorI signinValidator;

	@RequestMapping("/verify")
	@POST
	@ResponseBody
	@Override
	public TokenVerifyResponse verify(@RequestBody TokenVerifyRequest request) {
		TokenVerifyResponse response = new TokenVerifyResponse();

		boolean valid = this.authorizeService.verify(request.getToken());
		response.setValid(valid);
		return response;
	}

	@RequestMapping("/signin")
	public ModelAndView signin() {
		ModelAndView mv = new ModelAndView("api/signin");

		List<KeyValuePair> paramList = new LinkedList<>();
		String[] paramNames = SigninParamEnum.paramNames();
		for (String pname : paramNames) {
			String value = httpRequest.getParameter(pname);
			if (value != null) {
				paramList.add(new KeyValuePair(pname, value));
			}
		}
		mv.addObject("paramList", paramList);
		mv.addObject(SigninParamEnum.SESSION_ID.getParam(), httpRequest.getParameter(SigninParamEnum.SESSION_ID.getParam()));
		if (httpRequest.getAttribute("signinResult") == null) {
			mv.addObject("signinResult", null).addObject("presetGuser", null).addObject("presetGaccess", null);
		}
		return mv;
	}

	@RequestMapping("/dsignin")
	public ModelAndView dsignin(GeneralUserVo guser, GeneralAccessVo gaccess) {
		ModelAndView mv = new ModelAndView();
		try {
			ValidateResult vr = this.signinValidator.validate(guser, gaccess);
			if (vr.isValid()) {
				this.authorizeService.dsignin(guser, gaccess, httpResponse);
				mv.setViewName(String.format("redirect:%s", gaccess.getReturnUrl()));
			} else if (vr.getEcode() != null && vr.getEcode().equals(SigninErrorTypeEnum.userError.name())) {
				log.info("登录失败,用户输入有误：", vr.getEmsg());
				mv.setViewName(String.format("forward:%s", GorgeousParameters.AUTH_SIGNGIN_PATH));
				mv.addObject("signinResult", vr).addObject("presetGuser", guser).addObject("presetGaccess", gaccess);
			} else if (vr.getEcode() != null && vr.getEcode().equals(SigninErrorTypeEnum.appError.name())) {
				log.info("登录失败,会话应用请求有误：{}", vr.getEmsg());
			}
		} catch (Exception e) {
			log.error("登录失败,用户输入有误。", e);
			mv.setViewName(String.format("redirect:%s", gaccess.getReturnUrl()));
		}
		return mv;
	}

	@RequestMapping({ "/ivc" })
	@ResponseBody
	public void ivc(String sid) {
		if (sid != null && !sid.equals("")) {
			this.authorizeService.ivCode(sid, httpResponse);
		}
	}

	@RequestMapping("/signout")
	@ResponseBody
	@Override
	public ProcessResult signout(String sid) {
		try {
			this.authorizeService.signout(sid);
		} catch (Exception e) {
			log.error("退出登录失败。", e);
		}
		return new ProcessResult(true, "退出登录成功。");
	}

	@RequestMapping("/cuser")
	@ResponseBody
	@Override
	public GeneralUserVo cuser(String sid) {
		return this.authorizeService.getCurrentUser(sid);
	}

}
